/************************************************************
 * Project Name         [Thinking_In_Java]
 * File Name            [Java_IO_Object_Input_Output_Stream.java]
 * Creation Date        [07-Jul-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ************************************************************/
package pkg_09_io.api;

import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * java.io.ObjectInputStream<br>
 * java.io.ObjectOutputStream<br>
 * 
 * 这两个类用于对象的序列化和反序列化
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class Java_IO_Object_Input_Output_Stream {

	/**
	 * 对象序列化
	 */
	public static void writeObject() {
		ObjectOutputStream out = null;

		try {
			out = new ObjectOutputStream(new FileOutputStream("object.data"));

			out.writeObject(new Student("Sean Yang", "SUFE", 30));
			out.writeObject(new Student("Sean Yang", "TYWZ", 18));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 对象反序列化
	 */
	public static void readObject() {
		ObjectInputStream in = null;

		try {
			in = new ObjectInputStream(new FileInputStream("object.data"));

			Student student = null;
			try {
				while (in.available() != -1) {
					student = (Student) in.readObject();
					System.out.println(student);
				}
			} catch (EOFException e) {
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		writeObject();
		readObject();

	}
}

/**
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
class Student implements Serializable {

	private static final long serialVersionUID = 5306399104161924777L;

	private final String name;
	private final String schoolName;
	private final Integer age;

	public Student(String name, String schoolName, Integer age) {
		super();
		this.name = name;
		this.schoolName = schoolName;
		this.age = age;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", schoolName=" + schoolName
				+ ", age=" + age + "]";
	}
}